<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <input type="text" id="searchInput" style="position:relative;"/>
    <div style="width: 177px;height: 160px" id="inner"></div>
</div>
<script>
    let count = 0
    const input = document.getElementById('searchInput')
    //? 词库
    let arr = ['zhang','tang','zz']
    //? 监听input事件
    input.oninput = function () {
        const inputValue = input.value
        //? 有input框，需要开始联想
        if (inputValue !== "") {
            count = countHits(inputValue, arr)
            const inner = document.getElementById('inner');
            inner.innerHTML = ''; //? 清空原有选项
            //? 遍历词库 找前缀
            for (let i = 0; i < arr.length; i++) {
                //? 前缀存在，联想出来
                if (arr[i].startsWith(inputValue)) {
                    //? 创造button 加入联想框中
                    const newElement = document.createElement('button');
                    newElement.textContent = arr[i];
                    newElement.setAttribute('class','new')
                    //? block是为了让他独占一行
                    newElement.setAttribute('style','display:block')
                    inner.appendChild(newElement);
                }
            }
            //? 为联想词设置点击事件，将其填充进input框，并清空联想
            let newV = document.getElementsByClassName('new')
            Array.from(newV).forEach(item => {
                item.onclick = function changeF() {
                    input.value = item.innerText
                    inner.innerHTML = ''
                }
            })
        }
        //? 当input框为空的时候，需要把所有联想清空
        else {
            document.getElementById('inner').innerHTML = ''; //? 清空原有选项
        }
    }
    function countHits(value, arr) {
        for (let i = 0; i < arr.length; i ++) {
            if (arr[i].startsWith(value)) {
                count++
            }
        }
        return count;
    }

</script>
</body>
</html>
